package com.example.managemyself.ui.ai;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.activity.OnBackPressedCallback;

import com.example.managemyself.R;
import com.example.managemyself.data.model.AIConversation;
import com.example.managemyself.data.model.AIMessage;
import com.example.managemyself.data.model.User;
import com.example.managemyself.util.AIDataManager;
import com.example.managemyself.util.DeepSeekHelper;
import com.example.managemyself.util.UserManager;
import com.example.managemyself.util.ChatHistoryManager;
import com.example.managemyself.util.AITaskManager;
import com.example.managemyself.util.PersonalAIAssistant;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class AIChatFragment extends Fragment {

    private RecyclerView rvMessages;
    private EditText etMessage;
    private ImageButton btnSend;
    private ProgressBar progressBar;
    
    private List<ChatMessage> messages = new ArrayList<>();
    private ChatAdapter adapter;
    private Handler mainHandler = new Handler(Looper.getMainLooper());
    
    private AIConversation currentConversation;
    private boolean isNewConversation = true;
    private ChatHistoryManager historyManager;
    private AITaskManager aiTaskManager;
    private PersonalAIAssistant personalAssistant;
    private String currentConversationId;
    private boolean hasModifiedTitle = false;
    private boolean hasUserInteraction = false;
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        historyManager = new ChatHistoryManager(requireContext());
        aiTaskManager = new AITaskManager(requireContext());
        personalAssistant = PersonalAIAssistant.getInstance(requireContext());
        
        // 处理返回按钮拦截
        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                handleBackPressed();
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ai_chat, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        initViews(view);
        setupRecyclerView();
        loadConversation();
    }
    
    @Override
    public void onPause() {
        super.onPause();
        
        // 不在这里处理保存确认，因为onPause会在很多情况下被调用
        // 保存确认逻辑移到handleBackPressed和菜单导航中
    }
    
    @Override
    public void onStop() {
        super.onStop();
        
        // 自动清理空对话
        cleanupEmptyConversationsIfNeeded();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        
        // 最终清理检查
        if (currentConversationId != null && !hasUserInteraction) {
            // 如果用户从未发送消息，删除这个空对话
            historyManager.deleteConversation(currentConversationId);
        }
    }
    
    private void initViews(View view) {
        rvMessages = view.findViewById(R.id.rvMessages);
        etMessage = view.findViewById(R.id.etMessage);
        btnSend = view.findViewById(R.id.btnSend);
        progressBar = view.findViewById(R.id.progressBar);
        
        btnSend.setOnClickListener(v -> sendMessage());
    }
    
    private void setupRecyclerView() {
        adapter = new ChatAdapter(messages);
        rvMessages.setLayoutManager(new LinearLayoutManager(requireContext()));
        rvMessages.setAdapter(adapter);
    }
    
    private void loadConversation() {
        Bundle args = getArguments();
        if (args != null) {
            String conversationId = args.getString("conversation_id");
            String initialQuery = args.getString("initial_query");
            String initialResponse = args.getString("initial_response");
            
            if (conversationId != null) {
                // 加载现有对话
                loadExistingConversation(conversationId);
            } else if (initialQuery != null && initialResponse != null) {
                // 从轮盘传递过来的初始对话
                addUserMessage(initialQuery);
                addAIMessage(initialResponse);
                createNewConversation("轮盘卜卦对话");
            } else {
                // 新对话
                addSystemMessage("您好！我是您的AI助手，有什么可以帮助您的吗？");
                createNewConversation("新对话");
            }
        } else {
            // 新对话 - 个性化欢迎
            User currentUser = UserManager.getInstance().getCurrentUser();
            String welcomeMessage = "您好" + (currentUser != null ? currentUser.getDisplayName() : "") + 
                "！我是您的贴身AI助手，对您的生活了如指掌。\n\n" +
                "🤖 我能为您做什么：\n" +
                "• 回答关于您日记、任务的问题\n" +
                "• 管理您的任务（添加、查询、删除、修改）\n" +
                "• 基于您的历史记录提供个性化建议\n" +
                "• 了解您最近的活动和完成情况\n\n" +
                "💡 试试问我：\n" +
                "• \"我最近写了什么日记？\"\n" +
                "• \"我有什么未完成的任务？\"\n" +
                "• \"添加任务：学习英语\"\n" +
                "• \"我这几天做了什么？\"";
            addSystemMessage(welcomeMessage);
            createNewConversation("新对话");
        }
    }
    
    private void createNewConversation(String title) {
        currentConversationId = historyManager.createNewConversation(title);
        isNewConversation = false;
    }
    
    private void loadExistingConversation(String conversationId) {
        currentConversationId = conversationId;
        List<ChatHistoryManager.ChatMessage> historyMessages = historyManager.getConversationMessages(conversationId);
        
        messages.clear();
        for (ChatHistoryManager.ChatMessage historyMsg : historyMessages) {
            ChatMessage chatMsg = new ChatMessage(
                historyMsg.getType(), 
                historyMsg.getContent(), 
                historyMsg.getTimestamp()
            );
            messages.add(chatMsg);
        }
        
        adapter.notifyDataSetChanged();
        if (!messages.isEmpty()) {
            rvMessages.smoothScrollToPosition(messages.size() - 1);
        }
        
        isNewConversation = false;
    }
    
    private void sendMessage() {
        String content = etMessage.getText().toString().trim();
        if (content.isEmpty()) {
            return;
        }
        
        // 标记用户已有交互
        hasUserInteraction = true;
        
        // 添加用户消息
        addUserMessage(content);
        
        // 保存用户消息到历史记录
        if (currentConversationId != null) {
            historyManager.addMessage(currentConversationId, ChatMessage.TYPE_USER, content);
        }
        
        // 清空输入框
        etMessage.setText("");
        
        // 显示加载状态
        progressBar.setVisibility(View.VISIBLE);
        
        // 检查是否是任务管理相关的请求
        if (isTaskManagementRequest(content)) {
            handleTaskManagementRequest(content);
            return;
        }
        
        // 使用个人助手增强消息上下文
        personalAssistant.enhanceAIMessage(content, enhancedMessage -> {
            // 使用DeepSeek助手进行对话
            DeepSeekHelper.getChatResponse(enhancedMessage, new DeepSeekHelper.DeepSeekCallback() {
                @Override
                public void onResponse(String response) {
                    mainHandler.post(() -> {
                        progressBar.setVisibility(View.GONE);
                        addAIMessage(response);
                        
                        // 保存AI回复到历史记录
                        if (currentConversationId != null) {
                            historyManager.addMessage(currentConversationId, ChatMessage.TYPE_AI, response);
                        }
                    });
                }

                @Override
                public void onError(String error) {
                    mainHandler.post(() -> {
                        progressBar.setVisibility(View.GONE);
                        String errorMsg = "抱歉，发生了一个错误：" + error;
                        addSystemMessage(errorMsg);
                        
                        // 保存错误消息到历史记录
                        if (currentConversationId != null) {
                            historyManager.addMessage(currentConversationId, ChatMessage.TYPE_SYSTEM, errorMsg);
                        }
                    });
                }
            });
        });
    }
    
    private void addUserMessage(String content) {
        ChatMessage message = new ChatMessage(ChatMessage.TYPE_USER, content, getCurrentTime());
        messages.add(message);
        adapter.notifyItemInserted(messages.size() - 1);
        rvMessages.smoothScrollToPosition(messages.size() - 1);
    }
    
    private void addAIMessage(String content) {
        ChatMessage message = new ChatMessage(ChatMessage.TYPE_AI, content, getCurrentTime());
        messages.add(message);
        adapter.notifyItemInserted(messages.size() - 1);
        rvMessages.smoothScrollToPosition(messages.size() - 1);
    }
    
    private void addSystemMessage(String content) {
        ChatMessage message = new ChatMessage(ChatMessage.TYPE_SYSTEM, content, getCurrentTime());
        messages.add(message);
        adapter.notifyItemInserted(messages.size() - 1);
        rvMessages.smoothScrollToPosition(messages.size() - 1);
    }
    
    private String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
        return sdf.format(new Date());
    }
    
    /**
     * 判断是否是任务管理相关的请求
     */
    private boolean isTaskManagementRequest(String content) {
        String lowerContent = content.toLowerCase();
        return lowerContent.contains("任务") || 
               lowerContent.contains("添加") || 
               lowerContent.contains("删除") || 
               lowerContent.contains("修改") || 
               lowerContent.contains("查询") || 
               lowerContent.contains("创建") || 
               lowerContent.contains("新建") ||
               lowerContent.contains("完成") ||
               lowerContent.contains("更新") ||
               lowerContent.contains("管理");
    }
    
    /**
     * 处理任务管理请求
     */
    private void handleTaskManagementRequest(String content) {
        aiTaskManager.processTaskRequest(content, new AITaskManager.TaskOperationCallback() {
            @Override
            public void onSuccess(String message) {
                mainHandler.post(() -> {
                    progressBar.setVisibility(View.GONE);
                    addAIMessage("🤖 " + message);
                    
                    // 保存AI回复到历史记录
                    if (currentConversationId != null) {
                        historyManager.addMessage(currentConversationId, ChatMessage.TYPE_AI, "🤖 " + message);
                    }
                });
            }
            
            @Override
            public void onError(String error) {
                mainHandler.post(() -> {
                    progressBar.setVisibility(View.GONE);
                    addAIMessage("❌ " + error);
                    
                    // 保存错误消息到历史记录
                    if (currentConversationId != null) {
                        historyManager.addMessage(currentConversationId, ChatMessage.TYPE_AI, "❌ " + error);
                    }
                });
            }
        });
    }
    

    
    /**
     * 生成建议的对话标题
     */
    private String generateSuggestedTitle() {
        if (currentConversationId == null) {
            return null;
        }
        
        List<ChatHistoryManager.ChatMessage> messages = historyManager.getConversationMessages(currentConversationId);
        
        // 找到第一条用户消息作为标题建议
        for (ChatHistoryManager.ChatMessage message : messages) {
            if (message.getType() == ChatHistoryManager.ChatMessage.TYPE_USER) {
                String content = message.getContent();
                // 截取前20个字符作为标题
                if (content.length() > 20) {
                    return content.substring(0, 20) + "...";
                } else {
                    return content;
                }
            }
        }
        
        return null;
    }
    
    /**
     * 清理空对话（如果需要）
     */
    private void cleanupEmptyConversationsIfNeeded() {
        int cleanedCount = historyManager.cleanupEmptyConversations();
        if (cleanedCount > 0) {
            Toast.makeText(getContext(), "已自动清理 " + cleanedCount + " 个空对话", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.ai_chat_menu, menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        
        if (itemId == R.id.action_clear_chat) {
            clearChat();
            return true;
        } else if (itemId == R.id.action_chat_history) {
            showChatHistory();
            return true;
        } else if (itemId == R.id.action_save_conversation) {
            saveConversation();
            return true;
        }
        
        return super.onOptionsItemSelected(item);
    }
    
    private void clearChat() {
        messages.clear();
        adapter.notifyDataSetChanged();
        addSystemMessage("对话已清空。有什么可以帮助您的吗？");
        createNewConversation("新对话");
    }
    
    private void showChatHistory() {
        List<ChatHistoryManager.Conversation> conversations = historyManager.getAllConversations();
        
        if (conversations.isEmpty()) {
            Toast.makeText(getContext(), "暂无历史对话", Toast.LENGTH_SHORT).show();
            return;
        }
        
        String[] titles = new String[conversations.size()];
        for (int i = 0; i < conversations.size(); i++) {
            ChatHistoryManager.Conversation conv = conversations.get(i);
            titles[i] = conv.getTitle() + " (" + conv.getCreatedAt() + ")";
        }
        
        new AlertDialog.Builder(requireContext())
                .setTitle("历史对话")
                .setItems(titles, (dialog, which) -> {
                    ChatHistoryManager.Conversation selectedConv = conversations.get(which);
                    loadExistingConversation(selectedConv.getId());
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void saveConversation() {
        if (currentConversationId == null || messages.isEmpty()) {
            Toast.makeText(getContext(), "没有可保存的对话", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示输入对话标题的对话框
        EditText editText = new EditText(requireContext());
        editText.setHint("输入对话标题");
        
        // 显示当前标题（如果有）
        String currentTitle = historyManager.getConversationTitle(currentConversationId);
        if (currentTitle != null && !historyManager.hasDefaultTitle(currentConversationId)) {
            editText.setText(currentTitle);
        } else {
            // 生成建议标题
            String suggestedTitle = generateSuggestedTitle();
            if (suggestedTitle != null) {
                editText.setText(suggestedTitle);
            }
        }
        
        new AlertDialog.Builder(requireContext())
                .setTitle("保存对话")
                .setMessage("请为这个对话起一个标题：")
                .setView(editText)
                .setPositiveButton("保存", (dialog, which) -> {
                    String title = editText.getText().toString().trim();
                    if (title.isEmpty()) {
                        title = "对话 " + new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault()).format(new Date());
                    }
                    
                    // 使用自动保存方法，标记标题已修改
                    historyManager.markConversationTitleModified(currentConversationId, title);
                    hasModifiedTitle = true;
                    Toast.makeText(getContext(), "对话已保存", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    // 聊天消息类
    public static class ChatMessage {
        public static final int TYPE_USER = 0;
        public static final int TYPE_AI = 1;
        public static final int TYPE_SYSTEM = 2;
        
        private int type;
        private String content;
        private String timestamp;
        
        public ChatMessage(int type, String content, String timestamp) {
            this.type = type;
            this.content = content;
            this.timestamp = timestamp;
        }
        
        public int getType() {
            return type;
        }
        
        public String getContent() {
            return content;
        }
        
        public String getTimestamp() {
            return timestamp;
        }
    }
    
    // 聊天适配器
    public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.MessageViewHolder> {
        
        private List<ChatMessage> mMessages;
        
        public ChatAdapter(List<ChatMessage> messages) {
            mMessages = messages;
        }
        
        @NonNull
        @Override
        public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_message, parent, false);
            return new MessageViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {
            ChatMessage message = mMessages.get(position);
            
            // 设置发送者名称
            String sender;
            int textColor;
            int backgroundColor;
            
            switch (message.getType()) {
                case ChatMessage.TYPE_USER:
                    sender = "我";
                    textColor = R.color.black;
                    backgroundColor = R.color.user_message_bg;
                    holder.itemView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
                    break;
                case ChatMessage.TYPE_AI:
                    sender = "AI助手";
                    textColor = R.color.black;
                    backgroundColor = R.color.ai_message_bg;
                    holder.itemView.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
                    break;
                case ChatMessage.TYPE_SYSTEM:
                default:
                    sender = "系统";
                    textColor = R.color.white;
                    backgroundColor = R.color.system_message_bg;
                    holder.itemView.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
                    break;
            }
            
            holder.tvSender.setText(sender);
            holder.tvMessage.setText(message.getContent());
            holder.tvTimestamp.setText(message.getTimestamp());
            
            // 设置颜色
            holder.tvMessage.setTextColor(requireContext().getColor(textColor));
            holder.cardMessage.setCardBackgroundColor(requireContext().getColor(backgroundColor));
        }
        
        @Override
        public int getItemCount() {
            return mMessages.size();
        }
        
        public class MessageViewHolder extends RecyclerView.ViewHolder {
            android.widget.TextView tvSender;
            android.widget.TextView tvMessage;
            android.widget.TextView tvTimestamp;
            androidx.cardview.widget.CardView cardMessage;
            
            public MessageViewHolder(@NonNull View itemView) {
                super(itemView);
                tvSender = itemView.findViewById(R.id.tvSender);
                tvMessage = itemView.findViewById(R.id.tvMessage);
                tvTimestamp = itemView.findViewById(R.id.tvTimestamp);
                cardMessage = itemView.findViewById(R.id.cardMessage);
            }
        }
    }
    
    /**
     * 处理返回按钮按下事件
     */
    private void handleBackPressed() {
        if (currentConversationId != null && hasUserInteraction) {
            // 检查是否需要保存确认
            if (historyManager.isConversationWorthSaving(currentConversationId) && 
                historyManager.hasDefaultTitle(currentConversationId) && 
                !hasModifiedTitle) {
                
                showSaveConfirmationDialogOnExit();
                return;
            }
        }
        
        // 正常返回 - 使用Navigation返回上一级
        if (getParentFragmentManager().getBackStackEntryCount() > 0) {
            getParentFragmentManager().popBackStack();
        } else {
            requireActivity().onBackPressed();
        }
    }
    
    /**
     * 显示退出时的保存确认对话框
     */
    private void showSaveConfirmationDialogOnExit() {
        new AlertDialog.Builder(requireContext())
                .setTitle("保存对话")
                .setMessage("您要保存这段对话吗？如果不保存，对话内容将会丢失。")
                .setPositiveButton("保存", (dialog, which) -> {
                    showTitleInputDialogOnExit();
                })
                .setNegativeButton("不保存", (dialog, which) -> {
                    // 删除对话并退出
                    historyManager.deleteConversation(currentConversationId);
                    if (getParentFragmentManager().getBackStackEntryCount() > 0) {
                        getParentFragmentManager().popBackStack();
                    } else {
                        requireActivity().onBackPressed();
                    }
                })
                .setNeutralButton("取消", null)
                .setCancelable(true)
                .show();
    }
    
    /**
     * 退出时显示标题输入对话框
     */
    private void showTitleInputDialogOnExit() {
        EditText editText = new EditText(requireContext());
        editText.setHint("输入对话标题");
        
        // 根据对话内容生成建议标题
        String suggestedTitle = generateSuggestedTitle();
        if (suggestedTitle != null) {
            editText.setText(suggestedTitle);
        }
        
        new AlertDialog.Builder(requireContext())
                .setTitle("设置对话标题")
                .setMessage("为这个对话起一个标题：")
                .setView(editText)
                .setPositiveButton("保存并退出", (dialog, which) -> {
                    String title = editText.getText().toString().trim();
                    if (title.isEmpty()) {
                        title = "对话 " + new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault()).format(new Date());
                    }
                    
                    historyManager.markConversationTitleModified(currentConversationId, title);
                    hasModifiedTitle = true;
                    Toast.makeText(getContext(), "对话已保存", Toast.LENGTH_SHORT).show();
                    
                    // 退出
                    if (getParentFragmentManager().getBackStackEntryCount() > 0) {
                        getParentFragmentManager().popBackStack();
                    } else {
                        requireActivity().onBackPressed();
                    }
                })
                .setNegativeButton("取消", null)
                .setCancelable(true)
                .show();
    }
} 